package jbpClientTester;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class DataThread extends Thread {

	private Socket socket;
	public PrintWriter out;
	public BufferedReader in;
	private DataThread otherThread;
	private String name;

	public DataThread(Socket socket, String threadName) {

		super("DataThread");
		this.socket = socket;

		// each thread has a name, for debugging purposes mainly:
		name = threadName;

		System.out.println(name + " starting up...");
		
		try {

			out = new PrintWriter(socket.getOutputStream(), true);
			in = new BufferedReader(
					new InputStreamReader(socket.getInputStream()));

			this.start();

		} catch (IOException e) {
			e.printStackTrace();
			System.exit(1);
		}



	}

	public void run() {

		char line;
		try {				
			// when the thread reads something it tells its "otherThread" to send it
			while ( ( ( line = (char) in.read() ) != -20) && !socket.isClosed(  ) ) {
				System.out.println(">>> " + name+ " receiving data >>> " + line);
				otherThread.write(line);
			}
		} catch (Exception e) {
			try {
				in.close();
				out.close();
				this.socket.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} 
	}

	// Each thread has an "otherThread" to which it relays everything it receives:
	public void setOtherThread(DataThread other){
		otherThread = other;
	}

	// Send data:
	public void write(char data) {
		out.println(data);
		System.out.println(">>> " + name + " sending data >>>" + data);
	}
}